#include "timerclient.h"
#include "protocol.h"
#include <QDebug>
#include <QMessageBox>
#include <QDateTime>

TimerClient::TimerClient(QObject *parent)
    : QObject(parent),
    m_isConnected(false)
{
    m_socket = new QTcpSocket(this);
    connect(m_socket, SIGNAL(connected()), this, SLOT(handle_connected()));
    connect(m_socket, SIGNAL(disconnected()), this, SLOT(handle_disconnected()));
    connect(m_socket, SIGNAL(readyRead()), this, SLOT(handle_readyRead()));
    connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this,SLOT(handle_error(QAbstractSocket::SocketError)));
}

TimerClient::~TimerClient()
{
    delete m_socket;
}

void TimerClient::Connect(const QString &ip,int port)
{
    m_socket->connectToHost(ip, port);
}

void TimerClient::Disconnect()
{
    m_socket->disconnectFromHost();
}

bool TimerClient::isConnect()
{
    return m_isConnected;
}

int TimerClient::Send(const char* txt, int len)
{
    if (m_isConnected && txt)
    {
        m_socket->write(txt,len);
    }
    else
    {
        qDebug()<<"need connect";
        return -1;
    }

    return 0;
}

void TimerClient::handle_connected()
{
    m_isConnected = true;
    QString msg = m_Name + "@" + kTimerCmdRegister + "@connected";

    Send(msg.toLatin1().data(),msg.length());
    emit processMsg(m_Name,kTimerCmdRegister,"connected",m_diffTime);
}
void TimerClient::handle_disconnected()
{
    m_isConnected = false;
    m_socket->close();
}
void TimerClient::handle_readyRead()
{
    QString name, head,content;
    QByteArray message = m_socket->readAll();

    QList<QByteArray> blist= message.split('@');
    if(blist.size() == 3)
    {
        name = blist[0];
        head = blist[1];
        content = blist[2];

        emit processMsg(name,head,content,m_diffTime);
        if(head == kTimerCmdAuthorization)
        {
            //进行探测
            QString detect = m_Name + "@" + kTimerCmdDetect +"@test";

            m_detectTime = QDateTime::currentMSecsSinceEpoch();
            Send(detect.toLatin1().data(),detect.length());
        }
        else if(head == kTimerCmdDetect)
        {
            qint64 detectTime = QDateTime::currentMSecsSinceEpoch();
            m_diffTime=(detectTime-m_detectTime)/2;
        }
    }
}
void TimerClient::handle_error(QAbstractSocket::SocketError)
{
    //QMessageBox::information(QApplication::u, tr("show"), m_socket->errorString());
    handle_disconnected();
}
void TimerClient::SetName(const QString &name)
{
    m_Name = name;
}
